<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j con-box page-uc-collection">
    <!-- 头部标题-->
    <div class="footprint-head">
      <div class="head-tit">
        {{ $t('history.history') }}
      </div>

      <!-- 是否批量管理 -->
      <div
        v-if="!isBatchEdit"
        class="batch-btn"
        @click="openBatchEdit()"
      >
        {{ $t('collection.batchManagement') }}
      </div>
      <div
        v-if="isBatchEdit"
        class="action-btn-box"
      >
        <span class="batch-box">
          <span
            class="check"
            @click="selectAllItem()"
          >
            <input
              type="checkbox"
              class="checkbox default"
              :checked="isSelectedAll"
              :class="{ checked: isSelectedAll, default: !isSelectedAll }"
            >
            <span class="text">{{ $t('collection.selectAll') }}</span>
          </span>
          <span
            class="delete-collection"
            @click="showPopup()"
          >
            <i class="icon" />
            <span class="text">{{ $t('cart.deleteSelectedProducts') }}</span>
          </span>
          <span
            class="cancel-btn"
            @click="cancelBatchEdit"
          >{{ $t('cancel') }}</span>
        </span>
      </div>
    </div>
    <!-- 头部标题 end-->

    <!-- 收藏列表 -->
    <div
      v-for="(item, index) in browseLogData"
      :key="index"
      class="history-item"
    >
      <div class="time">
        {{ item.time.substr(0,10) }}
      </div>
      <div class="goods-list">
        <div class="list-con">
          <div
            v-for="(prodItem, prodIndex) in item.spuList"
            :key="prodIndex"
            :class="[
              'item',
              isBatchEdit ? 'batch-edit' : '',
              prodItem.isCheck ? 'checked' : '',
              selectedBrowseLogIds.includes(prodItem.prodBrowseLogId) ? 'checked' : ''
            ]"
            @click="selectProdItem(prodItem.prodBrowseLogId)"
          >
            <div
              class="goods-img"
              @click="toProdDetailPage(prodItem.prodId)"
            >
              <img-show :src="prodItem.pic" />
            </div>
            <div
              class="goods-msg"
              @click="toProdDetailPage(prodItem.prodId)"
            >
              <div class="goods-name">
                {{ prodItem.prodName }}
              </div>
              <div class="goods-price">
                <div class="price">
                  {{ '￥' + prodItem.price }}
                </div>
              </div>
            </div>
            <div class="goods-action">
              <div
                class="action-a a1"
                @click="toProdDetailPage(prodItem.prodId)"
              >
                <i class="icon" />{{ $t('collection.goToBuy') }}
              </div>
              <div
                class="action-a a2"
                @click="showPopup(prodItem.prodBrowseLogId, prodItem.prodId)"
              >
                <i class="icon" />{{ $t('history.deleteHistory') }}
              </div>
            </div>
            <div class="item-mask">
              <i class="icon" />
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- /收藏列表 -->

    <!-- 页码 -->
    <pagination
      v-if="pages > 1"
      v-model="pageNum"
      :pages="pages"
      @change-page="getBrowseProdList"
    />

    <!-- 空列表提示 -->
    <empty-all-tips
      v-if="isEmpty"
      :text="$t('history.historyEmpty')"
      :back="$t('lookAtOther')"
    />
    <!-- /空列表提示 -->

    <!-- 提示弹窗 -->
    <div
      v-if="isPopupVisible"
      class="popup-mask"
    />
    <div
      v-if="isPopupVisible"
      class="popup-box"
    >
      <div class="tit">
        <div class="text">
          {{ $t('tips') }}
        </div>
        <div
          class="close"
          @click="closePopup()"
        />
      </div>
      <div class="con">
        <div class="tip">
          <div class="tip-icon warning" />
          <div class="tip-info">
            <div class="result">
              {{ $t('userCenter.deleteTheSelected') }}
            </div>
            <div class="date">
              {{ $t('userCenter.deleteTheSelected') }}
            </div>
            <div class="btns">
              <a
                href="JavaScript:"
                class="btn-r"
                @click="deleteBrowseLog()"
              >{{ $t('userCenter.confirm') }}</a>
              <a
                href="JavaScript:"
                class="btn-g"
                @click="closePopup()"
              >{{ $t('userCenter.close') }}</a>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- /提示弹窗 -->
  </div>
</template>

<script setup>
import Cookie from 'vue-cookies'

onMounted(() => {
  document.title = $t('history.history')
  getBrowseProdList()
})

const isEmpty = ref(false)
const pageNum = ref(1)
const isSelectedAll = ref(false) // 是否选中全部
let browseLogList = []
const pages = ref(0)
const browseLogData = ref([]) // 按时间分割后的商品游览记录列表
const selectedBrowseLogIds = ref([]) // 选中的商品游览记录id列表
// 获取足迹商品列表
const getBrowseProdList = () => {
  isEmpty.value = false
  http.get('/p/prodBrowseLog/page', {
    params: {
      current: pageNum.value,
      size: 8
    }
  }).then(({ data }) => {
    isSelectedAll.value = false
    data.records.forEach((item) => {
      item.isCheck = false
    })
    const list = browseLogList = data.records
    isEmpty.value = !browseLogList.length
    pages.value = data.pages
    // 游览记录列表转换
    if (list.length) {
      convertBrowseLogList(list)
    } else {
      browseLogData.value = []
    }
  })
}

/**
 * 商品游览记录按时间来划分商品列表
 * 格式:[{time:time1,spuList:[]}, {time:time2,spuList:[]}]
 * @param {Array} list 商品列表
 */
const convertBrowseLogList = (list) => {
  let currentTime = list[0].browseTime
  let tempSpuList = []
  const browseLogDataPar = []
  for (let i = 0; i < list.length; i++) {
    if (currentTime === list[i].browseTime) {
      tempSpuList.push(list[i])
      if ((i + 1) === list.length) {
        const browseLogItem = {
          time: list[i].browseTime,
          spuList: tempSpuList
        }
        browseLogDataPar.push(browseLogItem)
      }
    } else {
      currentTime = list[i].browseTime
      const browseLogItem = {
        time: list[i - 1].browseTime,
        spuList: tempSpuList
      }
      browseLogDataPar.push(browseLogItem)
      tempSpuList = []
      tempSpuList.push(list[i])
      if ((i + 1) === list.length) {
        const browseLogItem = {
          time: list[i].browseTime,
          spuList: tempSpuList
        }
        browseLogDataPar.push(browseLogItem)
      }
    }
  }
  browseLogData.value = browseLogDataPar
}

const isBatchEdit = ref(false) // 是否批量修改
// 打开批量编辑
const openBatchEdit = () => {
  isBatchEdit.value = !isBatchEdit.value
}

// 取消批量编辑
const cancelBatchEdit = () => {
  selectedBrowseLogIds.value = []
  isBatchEdit.value = false
  isSelectedAll.value = false
  browseLogList.forEach((item) => {
    item.isCheck = false
  })
}

/**
 * 打开批量编辑，选择商品项
 * @param {Number} prodBrowseLogId 游览id
 */
const selectProdItem = (prodBrowseLogId) => {
  if (!isBatchEdit.value) {
    return
  }
  isSelectedAll.value = !isSelectedAll.value
  browseLogList.forEach(item => {
    if (item.prodBrowseLogId === prodBrowseLogId) {
      item.isCheck = !item.isCheck
      if (item.isCheck) {
        selectedBrowseLogIds.value = [...new Set([...selectedBrowseLogIds.value, item.prodBrowseLogId])]
      } else {
        selectedBrowseLogIds.value = selectedBrowseLogIds.value.filter(id => {
          return !(id === item.prodBrowseLogId)
        })
      }
    }
  })
  checkSelectedStatus()
}

// 选中全部选项
const selectAllItem = () => {
  isSelectedAll.value = !isSelectedAll.value
  browseLogList.forEach((item) => {
    item.isCheck = isSelectedAll.value
    if (item.isCheck) {
      selectedBrowseLogIds.value = [...new Set([...selectedBrowseLogIds.value, item.prodBrowseLogId])]
    } else {
      selectedBrowseLogIds.value = selectedBrowseLogIds.value.filter(id => {
        return !(id === item.prodBrowseLogId)
      })
    }
  })
}

// 检查是否全部选中
const checkSelectedStatus = () => {
  const prodList = browseLogList
  let isSelectedAllPar = true
  for (let i = 0; i < prodList.length; i++) {
    if (prodList[i].isCheck === false) {
      isSelectedAllPar = false
      break
    }
  }
  isSelectedAll.value = isSelectedAllPar
}

let selectedBrowseLogId = '' // 选中的商品游览记录id

let deleteLogType = '' // 删除类型 0:单个 1:批量
const isPopupVisible = ref(false) // 弹窗是否显示
/**
 * 弹出提示弹窗
 * @param {number} id 商品浏览记录id
 */
const showPopup = (id) => {
  if (id) {
    selectedBrowseLogId = id
    deleteLogType = 0 // 单个删除
    isPopupVisible.value = true
  } else {
    deleteLogType = 1 // 批量删除
    // 获取到批量提交的数据
    if (selectedBrowseLogIds.value.length > 0) {
      isPopupVisible.value = true
    } else {
      cancelBatchEdit() // 取消批量管理
    }
  }
}

// 隐藏提示弹窗
const closePopup = () => {
  isPopupVisible.value = false
}

// 删除商品游览记录
const deleteBrowseLog = () => {
  let spuBrowseLogIds = []
  if (deleteLogType === 0) {
    // 单个删除也用数组来传递传参
    spuBrowseLogIds.push(selectedBrowseLogId)
  } else {
    // 批量删除
    spuBrowseLogIds = selectedBrowseLogIds.value
  }
  const params = spuBrowseLogIds
  deleteTheProdRecord(params)
  isPopupVisible.value = false
}

// 删除足迹
const deleteTheProdRecord = (params) => {
  http.delete('/p/prodBrowseLog', {
    data: params
  }).then(() => {
    pageNum.value = 1
    getBrowseProdList()
    cancelBatchEdit()
  })
}

const router = useRouter()
const userStore = useUserStore()
// 跳转到商品详情页
const toProdDetailPage = (prodId) => {
  const newPage = router.resolve({ path: '/detail', query: { prodId } })
  let userId = null
  if (Cookie.get('bbcToken')) {
    userId = userStore.userId
  }
  http.get('/prod/prodInfo', {
    params: {
      prodId,
      userId
    }
  }).then(() => {
    window.open(newPage.href, '_blank', 'noopener,noreferrer')
  })
}

</script>

<style lang="scss" scoped>
@use "index";
</style>

<style lang="scss" scoped>
@use "../common/scss/user-center";
</style>
